import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:top_foundation/utils/ex/scroll_controller.dart';

class TPTabBarController {
  ///page切换完成时，值才会改变，可用于请求数据
  var index = 0.obs;
  RxInt previousIndex = 0.obs;

  ///page切换时，及时更新
  var current = 0;
  RxList<String> titles = [].cast<String>().obs;
  String get title {
    return titles.length <= current ? '' : titles[current];
  }

  late Map<int, Widget> pageMap;
  PageController? pageCtrl;
  ScrollController? scrollController;

  List<GlobalKey> keys = [];

  /// *[length]非必填，当item widget自定义时，必须填写
  TPTabBarController({
    int initialIndex = 0,
    bool isScrollable = false,
    bool needPage = true,
    int? length,
  }) {
    current = initialIndex;
    index.value = initialIndex;
    if (isScrollable) {
      scrollController = ScrollController();
    }
    if (needPage) {
      pageCtrl = PageController(initialPage: initialIndex)
        ..addListener(() {
          if (index.value != pageCtrl?.page) {
            previousIndex.value = index.value;
            index.value = pageCtrl?.page?.toInt() ?? 0;
          }
          locationTabbarVisiable();
        });
    }
    if (length != null && length > 0) {
      updateTitles(List.generate(length, (index) => '$index'));
    }
  }

  void actionTabItem(int idx) {
    if (index.value != idx) {
      current = idx;
      index.value = idx;
      if (idx != pageCtrl?.page) {
        pageCtrl?.jumpToPage(idx);
      }
    }
  }

  void locationTabbarVisiable() {
    var idx = index.value;
    var key = keys[idx];
    if (key.currentContext == null || scrollController == null) {
      return;
    }

    var box = key.currentContext!.findRenderObject() as RenderBox;
    var indexOffset =
        box.localToGlobal(Offset(box.size.width, box.size.height));

    var showWidth = scrollController!.position.extentInside;

    var extentBefore = scrollController!.position.extentBefore;

    //当前item中心距离屏幕左边距离
    var offsetLeft = indexOffset.dx - box.size.width / 2;
    //当前item中心距离屏幕中心距离
    var offsetCenter = offsetLeft - showWidth / 2;

    if (offsetCenter > 0) {
      offsetCenter += extentBefore;
    } else {
      offsetCenter = extentBefore + offsetCenter;
    }
    scrollController!.scrollTo(offsetCenter, isAnimate: true);
  }

  void updateTitles(List<String> titles) {
    this.titles.value = titles;
    keys = titles.map((e) => GlobalKey()).toList();
  }

  void dispose() {
    pageCtrl?.dispose();
    scrollController?.dispose();
  }
}
